import {
    createBuffer2,
} from './control'
import {
    createBuffer
} from '../params/control'
import {
    getMcu,
} from '../../api/login'
import {
    handleChangeLogs
} from './log'
// pages/bule/bule.js
Page({
    /**
     * 页面的初始数据
     */
    data: {
        uploadLog: false,
        scrollTop: 0,
        ver: '',
        devices: [],
        device: {},
        services: [],
        deviceId: '',
        serviceId: '',
        uuid: '',
        version: [],
        logs: [],
        files: [],
        flag: false,
        flag2: false,
        fainl: false,
        count: 0,
        total: 0,
        scrollIntoView: '', // 滚动到的视图id
        version: '',
        isAdmin: null,
        active: !true,
        totalSize: null, //文件长度
        sendArr: [],
        percent: 0,
        fileListArr: [],
        erroLogsLength: 0,
        uploadProgress: 0
    },

    // 转ascll
    hexToAscii(hexString) {
        let asciiString = '';
        for (let i = 0; i < hexString.length; i += 2) {
            let hex = hexString.substr(i, 2);
            let decimal = parseInt(hex, 16);
            asciiString += String.fromCharCode(decimal);
        }
        return asciiString;
    },
    onShow() {
        this.setData({
            deviceId: wx.getStorageSync('deviceId'),
            serviceId: wx.getStorageSync('serviceId'),
            uuid: wx.getStorageSync('uuid'),
            version: wx.getStorageSync('version'),
            isAdmin: wx.getStorageSync('isAdmin'),
        })
        if (!wx.getStorageSync('deviceId')) {
            this.setData({
                logs: []
            })
        }
        console.log(wx.getStorageSync('isAdmin'))
    },
    handleChangeipt(e) {
        this.setData({
            ver: e.detail.value
        })
    },
    // 写数据
    handleWrite(value, flag) {
        console.log(this.data, 'xxxxx')
        wx.writeBLECharacteristicValue({
            deviceId: this.data.deviceId,
            serviceId: this.data.serviceId,
            characteristicId: this.data.uuid,
            value,
            success: (res) => {
                if (!flag) {
                    wx.showToast({
                        title: '指令发送完成',
                        icon: 'none'
                    })
                }
                console.log(res, this.data.uuid, this.data.serviceId, '写入数据成功=========')
                this.handleWathc()
            },
            fail: (res) => {
                wx.showToast({
                    title: '写入数据失败',
                    icon: 'error'
                })
                console.log(res, this.data.uuid, this.data.serviceId, '写入数据失败')
            }
        })
    },

    decimalToHex(number) {
        const hex = number.toString(16);
        return hex.length === 1 ? '0' + hex : hex;
    },
    handleWathc() {
        const _this = this
        wx.notifyBLECharacteristicValueChange({
            deviceId: this.data.deviceId,
            serviceId: this.data.serviceId,
            characteristicId: this.data.uuid,
            state: true,
            type: "notification",
            success: (res) => {
                console.log(res, "notify创建连接-----------------------------------------------------")
            }
        })
        // 操作之前先监听，保证第一时间获取数据
        wx.onBLECharacteristicValueChange((result) => {
            this.setData({
                active: false
            })
            const res = new Uint8Array(result.value)
            wx.setStorageSync('isUpload', 1)
            console.log(res[0], res[1], res[2], res[3], '监听到了蓝牙升级页面,第0,1,2,3位-------------------------')
            console.log(res, '蓝牙升级接收信息，所有信息-------------------------')
            console.log(res.length, '信息长度-------------------------')
            // if (res.length > 3) {
            //     console.log('升级完成收到蓝牙版本', res)
            //     this.data.logs.push(`升级完成收到蓝牙版本${res}`)
            //     return
            // }
            if (res[0] === 6 && !res[1]) {

                if (this.data.flag) {
                    if (this.data.fainl) {
                        this.data.logs.push('MCU 应答并重启')
                        console.log('MCU 应答并重启')
                    }
                    if (this.data.count == (this.data.total - 1)) {
                        this.data.logs.push('文件块数已发完,MCU正在重启，请耐心等待,稍后查看参数设定版本')
                        wx.showToast({
                            title: '升级已完成，请等待',
                            icon: 'success'
                        })
                        console.log('文件块数已发完,MCU正在重启，请耐心等待')
                        this.handleWrite(createBuffer(5, 0x73, 0x01, [0x00]))
                        this.setData({
                            fainl: true,
                            files: [],
                            flag: false,
                            flag2: false,
                        })
                        this.setData({
                            logs: this.data.logs
                        })
                        return
                    }
                    if (!this.data.fainl) {
                        console.log('MCU 应答开始升级', this.data.count)
                        this.data.logs.push(`MCU 应答开始升级,第${this.data.count}块`)
                        if (this.data.count + 1 <= 255) {
                            const arr = new Uint8Array(this.data.files[this.data.count + 1])
                            const totalArr = []
                            arr.forEach(el => totalArr.push(el))
                            this.handleWrite(createBuffer2(134, 0x72, 0x82, 0x00, this.data.count + 1, totalArr))
                            this.setData({
                                count: this.data.count + 1,
                                percent: (this.data.count / this.data.total) * 100
                            })
                        } else {
                            console.log(this.data.count, '当前count')
                            const highByte = Math.floor((this.data.count + 1) / 256); // 高字节
                            const lowByte = (this.data.count + 1) % 256; // 低字节
                            const highHex = this.decimalToHex(highByte); // 高字节的16进制表示
                            const lowHex = this.decimalToHex(lowByte); // 低字节的16进制表示
                            const arr = new Uint8Array(this.data.files[this.data.count + 1])
                            const totalArr = []
                            console.log(highHex, lowHex, this.data.count + 1, '当前count+1的高低位')
                            console.log(typeof highHex, typeof lowHex, '的高低位高低位数据类型')
                            console.log(typeof parseInt(highHex), typeof parseInt(lowHex), '的高低位高低位数据类型2')

                            arr.forEach(el => totalArr.push(el))
                            this.handleWrite(createBuffer2(134, 0x72, 0x82, parseInt(highByte), parseInt(lowByte), totalArr))
                            this.setData({
                                count: this.data.count + 1,
                                percent: (this.data.count / this.data.total) * 100
                            })
                        }
                        this.autoScroll()
                    }
                } else {
                    console.log('MCU 确认可以进入升级----OK')
                    this.data.logs.push('MCU 确认可以进入升级----OK')
                }
                this.setData({
                    logs: this.data.logs
                })
            } else if (res[0] === 67 && !res[1] && res.length < 5) {
                this.data.logs.push('接收0x43,MCU 准备完成')
                this.data.logs.push('2S后DECODE 发送开始升级')
                console.log('接收0x43,MCU 准备完成')
                this.setData({
                    logs: this.data.logs
                })
                // DECODE 发送开始升级
                this.handleWrite(createBuffer(5, 0x71, 0x01, [0x00]))
            } else if (res[0] === 21) {
                this.data.logs.push('作中断重新开始升级，muc重启每隔1s发送0x43。')
                console.log('作中断重新开始升级，muc重启每隔1s发送0x43。')

                this.setData({
                    count: 0,
                    flag: false,
                    flag2: false,
                    fainl: false,
                })
                this.setData({
                    logs: this.data.logs
                })
            } else if (res[0] === 6 && res[1] === 67) {
                this.data.logs.push('已接收到06 43；MCU 应答开始升级')
                console.log('已接收到06 43；MCU 应答开始升级')
                const arr = new Uint8Array(this.data.files[0])
                const totalArr = []
                arr.forEach(el => totalArr.push(el))
                this.handleWrite(createBuffer2(134, 0x72, 0x82, 0x00, 0, totalArr))
                this.setData({
                    flag: true,
                    logs: this.data.logs,
                    count: this.data.count
                })
            } else if (res[0] == 46 && res[1] == 96 && res[3] != 1 && res.length > 5) {
                // 应答日志
                this.handleWrite(createBuffer(5, 0xe0, 0x01, [0x00]), true)
                console.log('正在接收日志，请等待', res)
                this.data.logs.push('正在接收日志' + result.value)
                console.log(res)
                this.data.fileListArr.push(res)
                this.setData({
                    logs: this.data.logs,
                    fileListArr: this.data.fileListArr,
                    uploadProgress: 80
                })
                this.autoScroll()
            } else if (res[0] == 46 && res[3] == 0 && res.length == 5) {
                this.data.logs.push('暂无日志')
                this.handleWrite(createBuffer(5, 0xe0, 0x01, [0x00]), true)
                wx.showToast({
                    title: '暂无日志',
                })
                this.setData({
                    logs: this.data.logs,
                })
            } else if (res[0] == 46 && res[3] == 3 && res.length == 5) {
                this.data.logs.push('日志接收完毕')
                this.handleWrite(createBuffer(5, 0xe0, 0x01, [0x00]), true)
                wx.showToast({
                    title: '接收完毕,准备上传',
                    duration: 3000
                })
                this.setData({
                    logs: this.data.logs,
                    uploadProgress: 100
                })
                this.hanleUpErrorLog()
                this.autoScroll()
            } else if (res[0] == 46 && res[3] == 1 && res.length == 9) {
                const str = res[4].toString(16) + '' + res[5].toString(16) + '' + res[6].toString(16) + '' + res[7].toString(16)
                console.log(str, '长度拼接')
                console.log(parseInt(str, 16), '长度拼接转10进制')
                this.setData({
                    erroLogsLength: parseInt(str, 16),
                    uploadLog: true, //日志遮罩打开
                    uploadProgress: 30
                })
                console.log(this.data.erroLogsLength, '总行数')
                this.data.logs.push(`日志总条数${this.data.erroLogsLength}`)
                this.data.logs.push(`请等待日志总条数上传完成后操作`)
                this.setData({
                    logs: this.data.logs,
                    uploadProgress: 50
                })
                this.handleWrite(createBuffer(5, 0xe0, 0x01, [0x00]), true)
            }
        })
    },
    hanleUpErrorLog() {
        console.log(this.data.fileListArr, '全部日志')
        // 数据转换
        let allLogArr = []
        if (this.data.fileListArr.length) {
            this.data.fileListArr.forEach(item => {
                allLogArr.push(Array.from(item))
            })
        }
        console.log(allLogArr, '全部日志--转化后10进制')
        // 将二维数组中的所有十进制数字转换为十六进制
        const hexadecimalArray = allLogArr.map(subArray => subArray.map(decimal => decimal.toString(16).padStart(2, '0')));
        // 输出转换后的十六进制二维数组
        console.log(hexadecimalArray, '全部日志--转化后16进制');
        // 处理每一条
        let logstr = ''
        hexadecimalArray.forEach(row => {
            // logstr+=handleChangeLogs(row)
            logstr += (JSON.stringify(row) + '\n\r')
        })
        console.log(logstr, '所有日志文本')
        const fs = wx.getFileSystemManager();
        const clxlh = wx.getStorageSync('clxlh')
        const filename = new Date().getTime() + `${clxlh}.txt`
        const filePath = wx.env.USER_DATA_PATH + `/${filename}`;
        const userId = wx.getStorageSync('userId')
        const token = wx.getStorageSync('token')
        const _this = this

        fs.writeFile({
            filePath: filePath,
            data: logstr,
            // data: new Uint8Array(allLogArr.flat()).buffer,
            encoding: 'utf8',
            success: function () {
                console.log('文件写入成功，调用上传接口');
                // 上传文件到服务器
                wx.uploadFile({
                    url: `https://www.ppdxy.cn/user/web/upload/log/file?userId=${userId}`,
                    filePath: filePath,
                    name: 'logFile',
                    header: {
                        'g-token': token
                    },
                    formData: {
                        userId: userId
                    },
                    success: function (res) {
                        if (!res.data.status) {
                            _this.setData({
                                uploadLog: false
                            })
                            wx.showModal({
                                title: '提示',
                                content: '文件上传成功',
                                complete: (res) => {
                                    if (res.cancel) {

                                    }
                                    if (res.confirm) {}
                                }
                            })
                        } else {

                        }
                        console.log('文件上传成功', res.data);
                        _this.setData({
                            uploadLog: false,
                            uploadProgress: 0,
                        })
                    },
                    fail: function (err) {
                        _this.setData({
                            uploadLog: false
                        })
                        console.error('文件上传失败', err);
                        wx.showModal({
                            title: '提示',
                            content: '文件上传失败',
                            complete: (res) => {
                                if (res.cancel) {

                                }
                                if (res.confirm) {}
                            }
                        })
                    }
                });
            },
            fail: function (err) {
                console.error('转换失败：', err);
                wx.showToast({
                    title: '文件转换失败',
                    duration: 3000,
                    icon: 'error'
                })
                _this.setData({
                    uploadLog: false
                })
            }
        });
    },
    readNextChunk(filePath, position, totalSize, count) {
        console.log(filePath, position, totalSize, count)
        this.setData({
            active: false,
            totalSize: totalSize
        })
        const length = Math.min(128, totalSize - position);
        const _this = this
        wx.getFileSystemManager().readFile({
            filePath: filePath,
            position: position,
            length: length,
            success: function (res) {
                const arrayBuffer = res.data;
                // 在这里处理二进制数据
                console.log(arrayBuffer);
                _this.data.files.push(arrayBuffer)
                // 继续读取下一个块
                const nextPosition = position + length;
                const nextCount = count + 1;
                if (nextPosition < totalSize) {
                    _this.readNextChunk(filePath, nextPosition, totalSize, nextCount);
                    wx.showLoading({
                        title: '文件处理中...',
                        duration: 100000000
                    })
                } else {
                    wx.hideLoading()
                    console.log(_this.data.files, 'files')
                    console.log('总共读取了' + nextCount + '个块');
                    _this.setData({
                        total: nextCount
                    })
                    wx.hideLoading()
                    // /如果最后一位不够128
                    if (_this.data.files[_this.data.files.length - 1].byteLength < 128) {
                        const arr = new Uint8Array(_this.data.files[_this.data.files.length - 1])

                        // 检查arr的字节长度是否小于128位
                        if (arr.byteLength < 128) {
                            // 创建一个新的Uint8Array，长度为128位
                            const paddedArray = new Uint8Array(128);
                            // 复制原始arr的数据到paddedArray
                            paddedArray.set(arr);
                            // 在paddedArray的末尾添加足够的0x00字节
                            for (let i = arr.byteLength; i < 128; i++) {
                                paddedArray[i] = 0x00;
                            }
                            console.log(paddedArray);
                            _this.data.files[_this.data.files.length - 1] = paddedArray.slice().buffer
                            console.log(_this.data.files)
                        }

                    }
                }
            },
            fail: function (error) {
                console.error(error);
            }
        });
    },
    handleGetFile() {
        console.log(this.data.ver)
        console.log(this.data.version)
        console.log(this.data.isAdmin)
        const arr1 = this.data.ver.split('_')
        const arr2 = this.data.version.split('_')
        console.log(arr1, arr2)
        if (this.data.isAdmin == 0 && (arr1[0] != arr2[0] || arr1[1] != arr2[1])) {
            wx.showToast({
                title: '版本不对',
                icon: 'error'
            })
            return
        }
        const _this = this
        this.setData({
            fainl: false,
            files: [],
            flag: false,
            flag2: false,
            count: 0,
            total: 0,
        })
        if (!this.data.ver) {
            wx.showToast({
                title: '请输入版本号',
                icon: 'error'
            })
            return
        }


        console.log(this.data.version, '当前版本')
        console.log(this.data.version.replace(/[^\x00-\x7F]/g, '').replace(/\s/g, ''), '当前版本去除乱码')
        getMcu({
            vername: this.data.ver,
            name: this.data.version.replace(/[^\x00-\x7F]/g, '').replace(/\s/g, '')
        }).then(res => {
            wx.showLoading({
                title: '正在获取文件',
            })
            if (!res) {
                wx.showLoading({
                    title: '未找到文件路径',
                })
                setTimeout(() => {
                    wx.hideLoading()
                }, 1000)
                return
            }
            if (res.fileUrl) {
                wx.downloadFile({
                    url: res.fileUrl,
                    success: function (res) {
                        console.log(res, 'xxx')
                        wx.hideLoading()
                        if (res.statusCode === 200) {
                            const filePath = res.tempFilePath;
                            const tempFilePath = filePath;
                            const totalSize = res.dataLength;
                            _this.setData({
                                logs: []
                            })
                            _this.readNextChunk(tempFilePath, 0, totalSize, 0);
                        } else {
                            wx.showToast({
                                title: '下载文件失败',
                            })
                            console.error('下载文件失败', res);
                        }
                    },
                    fail: function (err) {
                        wx.hideLoading()
                        console.error('下载文件失败', err);
                        wx.showToast({
                            title: '下载文件失败',
                        })
                    }
                });
            }
        })

    },
    handleGetFile2() {
        wx.chooseMessageFile({
            count: 1,
            success: res => {
                const file = res.tempFiles[0];
                const tempFilePath = file.path;
                const totalSize = file.size;
                this.readNextChunk(tempFilePath, 0, totalSize, 0);

            }
        })


    },
    handleClear() {
        this.setData({
            logs: []
        })
    },
    handleStart() {
        if (!this.data.files.length) {
            wx.showToast({
                title: '请先获取文件',
                icon: 'error'
            })
            return
        }
        // DECODE 通知 MCU 进入升级
        this.handleWrite(createBuffer(20, 0x70, 0x10, [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F]))



        this.setData({
            active: true,
            percent: 0
        })

    },
    handleLogout() {
        wx.showModal({
            title: '提示',
            content: '确定退出登录',
            complete: (res) => {
                if (res.cancel) {

                }

                if (res.confirm) {
                    wx.removeStorageSync('userId')
                    wx.removeStorageSync('token')
                    wx.removeStorageSync('cjh')
                    wx.removeStorageSync('lastLogin')
                    wx.removeStorageSync('canAddCjh')
                    wx.removeStorageSync('isAdmin')
                    wx.removeStorageSync('isUpload')
                    wx.navigateTo({
                        url: "/pages/login/login"
                    })
                }
            }
        })
    },
    handleAdd() {
        this.data.logs.push('xxxxxxxxxxx')
        this.setData({
            logs: this.data.logs
        })
        this.autoScroll()
    },
    //滚动条至最底部
    autoScroll() {
        var that = this
        let query = wx.createSelectorQuery()
        query.select('.messageScrollView').boundingClientRect(res => {
            console.log('res', res)
            that.setData({
                scrollTop: res.height * 100
            })
        })
        query.exec(res => {})

    },
    handleTest() {
        this.setData({
            count: this.data.count + 1,
            percent: (this.data.count / this.data.total) * 100
        })
    },
    handleLogsUpload() {
        this.data.logs = []
        this.data.logs.push(`发送请求logs数据命令`)
        this.setData({
            logs: this.data.logs
        })
        this.handleWrite(createBuffer(6, 0x90, 0x02, [0x60, 0x00]))
    }
})